<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 列表数据-->
      <el-table :data="userList" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} 可取到一行的数据-->
            <el-switch v-model="scope.row.mg_state" @change="switchChangeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 点击添加用户弹出的对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="35%" @close="addFormClose">
        <el-form :model="addUser" :rules="addUserRules" ref="addUserRef" label-width="65px">
          <el-form-item label="用户名" prop="username">
            <!-- 对话框里的表单 -->
            <el-input v-model="addUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" type="password">
            <el-input v-model="addUser.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUser.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model.number="addUser.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑修改用户信息 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="35%"
        @close="editFormClose"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="65px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        //合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    //验证手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        //合法的手机号
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 获取列表参数对象
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 1
      },
      userList: [],
      total: 0,
      //点击添加用户
      addDialogVisible: false,
      //添加用户
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //添加用户验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 9, message: '长度在 3 到 9 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 9, message: '长度在 5 到 9 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //编辑修改用户信息
      editDialogVisible: false,
      // 获取到的编辑修改用户信息对象
      editForm: {},
      //修改用户验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取管理员列表失败')
      //   this.$message.success(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    //pagesize改变事件
    handleSizeChange(newPage) {
      this.queryInfo.pagesize = newPage
      this.getUserList()
    },
    // pagenum改变事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听开关发生变化
    async switchChangeState(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // if(res.meta.status !== 200){
      //   userInfo.mg_state = !userInfo.mg_state
      //   return this.$message.error('状态设置失败')
      // }
      // this.$message.success(res.meta.ms)
      // console.log(res);
    },
    // 监听添加用户对话框关闭事件
    addFormClose() {
      this.$refs.addUserRef.resetFields()
    },
    //点击按钮，添加新用户
    addUsers() {
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return
        //发起添加用户的请求
        const { data: res } = await this.$http.post('/users', this.addUser)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        // console.log(res)
        // 隐藏对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    //修改用户信息
    async editUser(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('/users/' + id)
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editForm = res.data
    },
    // 监听编辑修改用户对话框关闭事件
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    //发起修改用户请求
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          '/users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        //隐藏修改用户对话框
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    //通过id删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      // console.log(confirmResult);   点击取消打印cancel   点击确定打印confirm
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const {data:res} = await this.$http.delete('/users/' + id)
      if(res.meta.status !==200) return this.$message.error('删除用户失败')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>